import { getUploadToken } from '@/common/api'
import type { AnyObject } from '@/common/types'

// 对更多字符编码的 url encode 格式
function camSafeUrlEncode(str:string) {
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A')
}

async function uploadFile(file:AnyObject, callback?:(fileUrl:string)=>void, type?:'technician-material') {
  const res = await getUploadToken(type)
  const { data } = res
  let names:string[]
  /* #ifdef H5*/
  names = file.name.split('.')
  /* #endif*/
  /* #ifdef APP-PLUS*/
  names = file.path.split('.')
  /* #endif*/
  const suffix:string = '.' + names[names.length - 1]
  data.realPath += suffix
  data.key += suffix

  return uni.uploadFile({
    url: 'https://' + data.url,
    filePath: file.path,
    name: 'file',
    formData: data,
    success: (res) => {
      if (type) {
        setTimeout(() => {
          const fileUrl = 'https://' + data.url + camSafeUrlEncode(data.realPath).replace(/%2F/g, '/')
          callback && callback(fileUrl)
        }, 2000)
      } else {
        const fileUrl = 'https://' + data.url + camSafeUrlEncode(data.realPath).replace(/%2F/g, '/')
        callback && callback(fileUrl)
      }
    }
  })
}

export default uploadFile
